package com.skp.shaphan.actions;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.skp.job.ProjectJobException;
import com.skp.shaphan.ShaphanApp;
import com.skp.shaphan.model.ConnectionDetails;
import com.skp.shaphan.ui.ConnectRunnable;
import com.skp.shaphan.ui.connectioncontrols.JTDSConnectionOptions;

/**
 * Creates a connection to a database
 * @author Stephen Phillips
 *
 */
public class JTDSConnectAction implements ConnectRunnable {
	private JTDSConnectionOptions optionsGUI;
	private Connection connection;
	
	/**
	 * Creates the new action attached to a specific dialog
	 * @param serverConnectionOptions the dialog containing the connection information
	 */
	public JTDSConnectAction(JTDSConnectionOptions serverConnectionOptions) {
		this.optionsGUI = serverConnectionOptions;
	}
	
	/**
	 * Creates the connection and attaches it to the SQL Editor
	 */
	@Override
	public void run() {
		connect();
		ShaphanApp.getMainWindow().getSQLEditorsPane().setConnection(new ConnectionDetails(connection, ConnectionDetails.CONN_TYPE_SQL_SERVER));
	}

	@Override
	public Connection connect() {
		try {
			Class.forName("net.sourceforge.jtds.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			(new ProjectJobException(e)).displayException();
		}
		String serverType = optionsGUI.getServerType();
		String serverName = optionsGUI.getServerName();
		String portNumber = optionsGUI.getPort().trim();
		if(portNumber.length() > 0) {
			portNumber = ":" + portNumber;
		}
		String userName = optionsGUI.getUser();
		String password = optionsGUI.getPassword();
		String databaseName = optionsGUI.getDatabaseName();
		if(databaseName != null && databaseName.trim().length() > 0) {
			databaseName = "/" + databaseName;
		}
		String version = optionsGUI.getVersion();
		if(version != null && version.trim().length() > 0) {
			version = ";TDS=" + version;
		}
		try {
			connection = DriverManager.getConnection("jdbc:jtds:" + serverType + "://" + serverName + portNumber + databaseName + version, userName, password);
		} catch (SQLException e) {
			(new ProjectJobException(e)).displayException();
		}
		return connection;
	}

}
